var myService = angular.module('myService', ['ui.router']);

myService.factory('http', ['$http', '$q', '$state', function($http, $q,$state) {
    function post(url, data) {
        function getPromise(url, data) {
            var deferred = $q.defer();
            var promise = deferred.promise;
            var h = { 'Content-Type': 'application/x-www-form-urlencoded' };
            var user_id = Cookies.get('user_id'),
                token = Cookies.get('token');
            if (user_id && token)
                h.Authorization = 'Basic ' + window.btoa(user_id + ':' + token);

            $http.post('/api' + url, data, {
                headers: h,
                transformRequest: function(data) {
                    return $.param(data);
                }
            }).success(function(data) {
                if (data.code === -1) {
                    $state.go('login');
                    return;
                }
                deferred.resolve(data);
            }).error(function(error) {
                deferred.reject(error);
            });
            return promise;
        }

        return getPromise(url, data);
    }

    function get(url) {
        function getPromise(url) {
            var deferred = $q.defer();
            var promise = deferred.promise;
            var h = { 'Content-Type': 'application/x-www-form-urlencoded' };
            var user_id = Cookies.get('user_id'),
                token = Cookies.get('token');
            if (user_id && token)
                h.Authorization = 'Basic ' + window.btoa(user_id + ':' + token);
            $http.get('/api' + url, {
                headers: h,
            }).success(function(data) {
                if (data.code === -1) {
                    $state.go('login');
                    return;
                }
                deferred.resolve(data);
            }).error(function(error) {
                deferred.reject(error);
            });
            return promise;
        }

        return getPromise(url);
    }

    return {
        get: get,
        post: post
    };
}]);